<template>
  <!--  定价方法匹配规则 -->
  <div>
    <el-row class="methodRule container">
      <!-- 左侧树 -->
      <el-col :span="6">
        <el-button @click="addOrEditFunc('1')">新增组</el-button>
        <vp-tree
          class="ie-tree-style"
          :vp-header="{
            show: true,
            text: '定价方法匹配规则组',
            search: true,
            name: 'ruleGroupName'
          }"
          :vp-title="'所有定价方法匹配规则组'"
          :filter-node-method="filterNode"
          :data="treeData"
          :props="defaultProps"
          default-expand-all
          ref="configTree"
          node-key="methodRuleGroup"
          :expand-on-click-node="false"
          check-on-click-node
          :render-content="rendertree"
        ></vp-tree>
      </el-col>
      <!-- 右侧表  -->
      <el-col :span="17" class="content-left" :offset="1">
        <methodRule
          ref="methodRuleList"
          :templateId="templateId"
          :methodRuleGroup="methodRuleGroup"
          :ruleGroupName="ruleGroupName"
        />
      </el-col>
    </el-row>
    <!-- 定价方法规则组新增、编辑弹窗 -->
    <el-dialog
      v-dialogDrag
      :title="methodRuleGroupTitleName"
      :visible.sync="methodRuleGroupAddOrEdit"
      width="40%"
    >
      <el-form
        :model="saveForm"
        ref="saveForm"
        label-width="100px"
        label-position="left"
        :rules="saveFormRules"
      >
        <el-col :span="15">
          <el-form-item label="规则组编号：" prop="methodRuleGroup">
            <el-input
              v-model.trim="saveForm.methodRuleGroup"
              maxlength="40"
              :disabled="operateType == 2"
            ></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="24">
          <el-form-item
            >（提示：只能输入字母、数字及下划线，最长字符数为40位）</el-form-item
          >
        </el-col>
        <el-col :span="15">
          <el-form-item label="规则组名称：" prop="ruleGroupName">
            <el-input
              v-model.trim="saveForm.ruleGroupName"
              maxlength="40"
            ></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="24">
          <el-form-item
            >（提示：只能输入汉字、字母、数字及下划线，最长字符数40）</el-form-item
          >
        </el-col>
        <el-col :span="15">
          <el-form-item label="规则模板：" prop="templateId">
            <el-select
              v-model="saveForm.templateId"
              placeholder="请选择"
              :title="saveTemplatesStr"
              class="saveTempName2"
              ref="saveTempNameRef"
              @focus="setWidth"
              multiple
            >
              <el-option
                :style="{width: optionwidth}"
                class="saveTempOption"
                v-for="item in templateIds"
                :key="item.templateId"
                :label="item.templateName"
                :value="item.templateId"
                :title="item.templateName"
              ></el-option>
            </el-select>
          </el-form-item>
        </el-col>
      </el-form>
      <div slot="footer">
        <el-button @click="saveFunc">确 定</el-button>
        <el-button @click="methodRuleGroupAddOrEdit = false">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { ruleTemplate } from "@/api/index";
import upperTemplate from "@/components/upperTemplate.vue";
import onlyOneSearch from "@/components/onlyOneSearch";
import methodRule from "./methodRule";
import moment from "moment";
export default {
  //定义数据
  data() {
    return {
      // 右侧树data
      treeData: [],
      defaultProps: {
        children: "children",
        label: "curveName"
      },
      methodRuleGroupTitleName: "",
      methodRuleGroupAddOrEdit: false,
      //规则组模板保存数据
      saveForm: {
        methodRuleGroup: "",
        ruleGroupName: "",
        templateId: ""
      },
      //规则模板数据
      templateIds: [],
      //操作标识
      operateType: "",
      //表单字段规则校验
      saveFormRules: {
        methodRuleGroup: [
          { required: true, message: "该输入项为必输项", trigger: "blur" },
          {
            pattern: /^[a-zA-Z0-9_]{1,40}$/,
            message: "只可输入(1-40)位的英文字母、数字和下划线！",
            trigger: "blur"
          },
          { validator: this.methodRuleGroupValid, trigger: "blur" }
        ],
        ruleGroupName: [
          { required: true, message: "该输入项为必输项", trigger: "blur" },
          {
            max: 100,
            message: "输入字符超过数据库设定最大长度",
            trigger: "blur"
          },
          {
            pattern: /^[a-zA-Z0-9_\u4e00-\u9fa5]+$/,
            message: "只可输入字母汉字数字_！",
            trigger: "blur"
          }
        ],
        templateId: [
          { required: true, message: "该输入项为必输项", trigger: "blur" }
        ]
      },
      //原规则组名称
      ruleGroupNameOld: "",
      templateId: "",
      methodRuleGroup: "",

      //查询时默认条件
      searchForm: {
        page: 1,
        size: 15,
        templateType: 1,
        templateCode: "",
        templateName: ""
      },
      total: 0,
      tableData: [],
      //弹窗标识
      ruleTemplateDi: false,
      //新增编辑弹出框名称
      titleName: "",
      //操作标识
      operateType: 1,
      //当前选中数据
      templateId: "",
      templateCode: "",
      templateName: "",
      ruleGroupName: "",
      optionwidth: "",
    };
  },
  //组件引入
  components: {
    onlyOneSearch,
    methodRule
  },
  //创建初始化
  created() {
    this.treeDataInit();
    this.templateIdsInit();
  },
  mounted() {},
  //监控数值变化
  watch: {},
  //运算
  computed: {
    saveTemplatesStr() {
      let ary = this.saveForm.templateId,
        str = "";
      if (
        Object.prototype.toString.call(this.saveForm.templateId) ===
        "[object Array]"
      ) {
        return this.saveForm.templateId
          .map(v =>
            this.$getLabel(v, this.templateIds, "templateId", "templateName")
          )
          .toString();
      } else {
        return "abc";
      }
    }
  },
  methods: {

    setWidth(){
          this.optionwidth = this.$refs.saveTempNameRef.$el.clientWidth+"px";
           
      },

    //树节点筛选执行的方法
    filterNode(value, data) {
      if (!value) return true;
      return data.label.indexOf(value) !== -1;
    },
    handleNodeClick(obj) {
      // 单选处理
      if (
        obj.parentMethodRuleGroup != "" &&
        obj.parentMethodRuleGroup != "root"
      ) {
        this.templateId = obj.methodRuleGroup;
        this.methodRuleGroup = obj.parentMethodRuleGroup;
        this.ruleGroupName = obj.ruleGroupName;
        setTimeout(() => {
          this.$refs.methodRuleList.searchFunc();
        }, 10);
      } else {
        this.$message.warning("请选择规则组下的规则模板");
        this.templateId = "";
      }
    },
    rendertree(h, { node, data, store }) {
      return (
        <span title={data.ruleGroupName}>
          <span
            style="margin-right:10px"
            on-click={() => this.handleNodeClick(data)}
          >
            {this.stringFixed(data.ruleGroupName)}
          </span>
          <i
            style="margin-right:10px"
            class="el-icon-edit"
            on-click={() => this.editRuleGroup(data)}
          ></i>
          <i
            class="el-icon-delete"
            on-click={() => this.deleteRuleGroup(data)}
          ></i>
        </span>
      );
    },
    stringFixed(v){
      let str ="";
      if(v.length>20){
        str = v.substring(0,20)+'...'
      }else{
        str = v
      }
      return str
    },
    editRuleGroup(obj) {
      if (obj.parentMethodRuleGroup == "root") {
        if (this.$refs.saveForm) {
          this.$refs.saveForm.resetFields();
        }
        this.ruleGroupNameOld = obj.ruleGroupName;
        this.operateType = "2";
        this.methodRuleGroupTitleName = "修改定价方法规则组信息";
        this.methodRuleGroupAddOrEdit = true;
        let data = {
          operateType: "2",
          methodRuleGroup: obj
        };
        ruleTemplate.toForm(data).then(res => {
          if (res.code === 200) {
            this.saveForm = res.datas.methodRuleGroup;
            this.$set(
              this.saveForm,
              "templateId",
              res.datas.templateId.split(",")
            );
          }
        });
      } else {
        return this.$message.warning("只可以修改规则组信息!");
      }
    },
    deleteRuleGroup(obj) {
      if (obj.parentMethodRuleGroup == "") {
        return this.$message.warning("根节点不可删除!");
      } else if (obj.parentMethodRuleGroup == "root") {
        let data = {
          methodRuleGroup: obj.methodRuleGroup,
          delType: "1"
        };
        ruleTemplate.methodRuleGroupCheckUsing(data).then(res => {
          if (res.code == 200) {
            if (res.data == "1") {
              return this.$message.warning("数据被情景管理引用，无法删除!");
            } else {
              this.$confirm("确定要删除数据吗", "提示", {
                confirmButtonText: "确定",
                cancelButtonText: "取消",
                type: "warning"
              })
                .then(() => {
                  ruleTemplate.methodRuleGroupRemove(data).then(res => {
                    if (res.code == 200) {
                      this.$message.success("删除成功");
                      this.treeDataInit();
                    } else {
                      this.$message.error(res.message || "删除失败");
                    }
                  });
                })
                .catch(() => {
                  this.$message({
                    type: "info",
                    message: "已取消删除"
                  });
                });
            }
          }
        });
      } else {
        let data = {
          delType: "2",
          uuid: obj.ruleGroupTemplateId,
          methodRuleGroup: obj.methodRuleGroup
        };
        ruleTemplate.methodRuleGroupCheckUsing(data).then(res => {
          if (res.code == 200) {
            if (res.data == "1") {
              return this.$message.warning("数据被情景管理引用，无法删除!");
            } else {
              this.$confirm("确定要删除数据吗", "提示", {
                confirmButtonText: "确定",
                cancelButtonText: "取消",
                type: "warning"
              })
                .then(() => {
                  ruleTemplate.methodRuleGroupRemove(data).then(res => {
                    if (res.code == 200) {
                      this.$message.success("删除成功");
                      this.treeDataInit();
                    } else {
                      this.$message.error(res.message || "删除失败");
                    }
                  });
                })
                .catch(() => {
                  this.$message({
                    type: "info",
                    message: "已取消删除"
                  });
                });
            }
          }
        });
      }
    },
    treeDataInit() {
      this.templateId = "";
      ruleTemplate.methodRuleGroupTree().then(res => {
        if (res.code === 200) {
          let list = res.datas;
          this.treeData = this.$listToTree(
            "methodRuleGroup",
            "parentMethodRuleGroup",
            list
          );
        }
      });
    },
    addOrEditFunc(val) {
      if (this.$refs.saveForm) {
        this.$refs.saveForm.resetFields();
      }
      this.methodRuleGroupTitleName = "新增定价方法规则组信息";
      this.methodRuleGroupAddOrEdit = true;
      this.operateType = val;
    },
    //规则组编号验证
    methodRuleGroupValid(rule, value, callback) {
      if (this.operateType == "1") {
        let data = {
          methodRuleGroup: value
        };
        ruleTemplate.checkCode(data).then(res => {
          if (res.code === 200) {
            if (res.data == "1") {
              callback(new Error("编号已存在，无法使用！"));
            } else {
              callback();
            }
          }
        });
      } else {
        callback();
      }
    },
    //规则组名称验证
    ruleGroupNameValid(rule, value, callback) {
      if (
        this.operateType == "1" ||
        (this.operateType == "2" && this.ruleGroupNameOld != value)
      ) {
        let data = {
          ruleGroupName: value
        };
        ruleTemplate.checkNameUnique(data).then(res => {
          if (res.code === 200) {
            if (res.data == "1") {
              callback(new Error("此模板名称已存在，无法使用！"));
            } else {
              callback();
            }
          }
        });
      } else {
        callback();
      }
    },
    //模板类型初始化
    templateIdsInit() {
      let data = {
        templateType: "1"
      };
      ruleTemplate.findTemplataByType(data).then(res => {
        if (res.code === 200) {
          this.templateIds = res.datas;
        }
      });
      this.templateIds = [
        { templateId: "111", templateName: "111" },
        { templateId: "222", templateName: "222" },
        { templateId: "333", templateName: "333" }
      ];
    },
    //规则组保存
    saveFunc() {
      this.$refs["saveForm"].validate(valid => {
        if (valid) {
          this.checkNameUnique();
        }
      });
    },
    saveFuncConfirm() {
      let data = {
        operateType: this.operateType,
        templateId: this.saveForm.templateId.join(","),
        methodRuleGroup: { ...this.saveForm }
      };
      ruleTemplate.methodRuleGroupSave(data).then(res => {
        if (res.code == 200) {
          this.$message.success("保存成功");
          this.methodRuleGroupAddOrEdit = false;
          this.treeDataInit();
        } else {
          this.$message.error(res.message || "保存失败");
        }
      });
    },
    //规则组校验名称是否重复
    checkNameUnique() {
      if (
        this.operateType == "1" ||
        (this.operateType == "2" &&
          this.ruleGroupNameOld != this.saveForm.ruleGroupName)
      ) {
        let data = {
          ruleGroupName: this.saveForm.ruleGroupName
        };
        ruleTemplate.checkNameUnique(data).then(res => {
          if (res.code === 200) {
            if (res.data == "1") {
              this.$message.warning("此模板名称已存在，无法使用");
            } else {
              this.saveFuncConfirm();
            }
          }
        });
      } else {
        this.saveFuncConfirm();
      }
    },
    //   点击行选中
    authorizeFor(row) {
      if (this.$refs.multipleTable) {
        this.$refs.multipleTable.clearSelection();
      }
      this.$refs.multipleTable.toggleRowSelection(row, true);
    },
    //事件转换
    timeFormat(val) {
      if (val) return moment(val).format("YYYY-MM-DD HH:mm:ss");
      else return "";
    },
    //页码值改变
    handleSizeChange(val) {
      console.log(`每页 ${val} 条`);
      this.searchForm.size = val;
      this.searchFunc();
    },
    //当前页改变
    handleCurrentChange(val) {
      this.searchForm.page = val;
      console.log(`当前页: ${val}`);
      this.searchFunc();
    }
  }
};
</script>


<style lang="scss" scoped>
.el-table__header th {
  /deep/ .cell {
    white-space: nowrap !important;
  }
}

/deep/.el-dialog__body {
  max-height: 400px;
}
.tipMessage {
  line-height: 32px;
  margin-left: 5px;
  color: red;
  font-family: PingFangSC-Medium, PingFang SC;
  font-weight: 500 !important;
  font-size: 12px !important;
}
 

.saveTempName2 {
  width: 100%;

  /deep/.el-select__tags-text {
  display: inline-block;//设置成行内块
  max-width: 65px;//设置最大宽度
  overflow: hidden;//隐藏滚动条
  text-overflow: ellipsis;//将超出部分用...代替
  white-space: nowrap;//段落中的文本不进行换行
}
 
/deep/.el-select .el-tag__close.el-icon-close {
  top: -7px;
}

}


</style>